import React, {useState} from 'react'
import {useSelector} from 'react-redux'
import { View, Input, Editor, Button } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { AtImagePicker } from 'taro-ui'
import './index.scss'
import useAuth from '../../components/useAuth'
import {ReduxStateProps} from '../../reducers/index'

let editorCtx

 function addTie() {
  useAuth()
  const [files, setFiles] = useState([])
  const [title, setTitle] = useState('')
  const [content, setContent] = useState('')
  const user = useSelector((state: ReduxStateProps) => state.user)
  
  console.log('组件渲染：', editorCtx)

  const titleChange = (e) => {
    setTitle(e.target.value)
  }

  const editorReady = () => {
    Taro.createSelectorQuery().select('#editor').context((res) => {
      editorCtx = res.context
      console.log('富文本初始化', editorCtx)

      // editorCtx.setContents({
      //   html: '<p>手动初始化</p>'
      // })
    }).exec()
  }
  const contentChange = (e) => {
    console.log('富文本编辑input：', e)
    setContent(e.detail.html)
  }

  const onFileChange = (files) => {
    console.log('选择图片：', files)
    setFiles(files)
  }
  const onFileFail = (err) => {
    console.log('图片选择失败：', err)
  }

  const onImageClick = (index, file) => {
    console.log('图片点击：', index, file)
  }

  async function upLoadImages() {
    if(!files.length) return null

    let fileArr: Taro.cloud.UploadFileResult[] = []
    files.forEach((item) => {
      let m = String(Math.random()).substr(2)
      let filename = 'mytie/' + Date.now() + '-' + m + '.png'

      let a = Taro.cloud.uploadFile({
        cloudPath: filename, // 云空间路径
        filePath: item.url, // 文件路径
      })
      fileArr.push(a)
    })
    const uploadResult = await Promise.all(fileArr)
    console.log('所有图片上传成功：', uploadResult)
    return uploadResult
  }

  async function sendTiezi(filesRes) {
    console.log('图片存在：', filesRes)

    return await Taro.cloud.callFunction({
      name: 'tiezi',
      data: {
        type: 'insertTiezi',
        title,
        content,
        userId: user.userId,
        files: filesRes
      }
    })
  }

  // 发布
  async function submitTie() {
    if(!content) return Taro.showToast({
      title: '请输入内容',
      icon: 'loading'
    })

    const filesRes = await upLoadImages()
    const tieRes = await sendTiezi(filesRes)
    console.log('发布帖子结果：', tieRes)

    setFiles([])
    setTitle('')
    setContent('')
    console.log('editorCtx: ', editorCtx)
    editorCtx.setContents({
      html: ''
    })
  }

  return (
    <View className="add-tiezi">
        <View className="title-group">
          <Input placeholder="请输入标题" className="title" value={title} onInput={titleChange} />
        </View>

        <View className="edit-group">
          <Editor id="editor" className="edit" placeholder="请输入帖子内容" onReady={editorReady} onInput={contentChange} />
        </View>

        <View className="pic-group">
          <AtImagePicker
            multiple
            count={4}
            files={files}
            onChange={onFileChange}
            onFail={onFileFail}
            onImageClick={onImageClick}
          />
        </View>

        <View className="submit-group">
          <Button className="submit-btn" onClick={submitTie}>发布</Button>
        </View>
    </View>
  )
}

export default addTie